package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //谁看过我分页列表
    @Override
    public List<Visitors> findAll(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return  mongoTemplate.find(query, Visitors.class);
    }

    //谁看过我
    @Override
    public List<Visitors> findById(Long userId, Long time) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("date").gt(time))
                .with(Sort.by(Sort.Order.desc("date")))
                .limit(5);
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }

    //保存
    @Override
    public void save(Visitors visitors) {
        //判断记录是否存在
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        if (!mongoTemplate.exists(query, Visitors.class)) {
            mongoTemplate.save(visitors);
        }
    }
}
